package com.lanou.sfu.songforu.adapter;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.activity.MainActivity;
import com.lanou.sfu.songforu.datas.MusicListDatas;
import com.lanou.sfu.songforu.datas.ReconmmendSongDatas;
import com.lanou.sfu.songforu.datas.SongInfors;
import com.lanou.sfu.songforu.download.FileUtils;
import com.lanou.sfu.songforu.singleton.VolleySingleton;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by quyan on 15/10/27.
 */
public class RecommendSongAdapter extends BaseAdapter {
    private List<ReconmmendSongDatas.ContentEntity>datas;
    private Context context;
    private VolleySingleton volleySingleton;
    private static Button download;

    private String songsName;

    private static final String TAG = "DOWNLOADAPK";
    private String fileEx = "";
    private String fileNa = "";
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private static final int mNotificationID = 1;// 通知的id
    private RemoteViews mRemoteViews;


    public RecommendSongAdapter(Context context,List<ReconmmendSongDatas.ContentEntity> contentEntities) {
        this.context = context;
        datas = contentEntities;
        volleySingleton = VolleySingleton.getInstance(context);
    }

    @Override
    public int getCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.fragment_song_listviewitem,null);
            holder = new ViewHolder();
            holder.authersName = (TextView) convertView.findViewById(R.id.authersNames);
            holder.songsNames = (TextView) convertView.findViewById(R.id.songsNames);
            holder.songDow = (ImageView) convertView.findViewById(R.id.songDow);
            holder.itemSongListView = (LinearLayout) convertView.findViewById(R.id.itemSongListView);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        //根据下标取数据
        final ReconmmendSongDatas.ContentEntity songDats = (ReconmmendSongDatas.ContentEntity) getItem(position);
        holder.songsNames.setText(songDats.getTitle());
        holder.authersName.setText(songDats.getAuthor());
        //点击行布局将数据传到集合中
        holder.itemSongListView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<MusicListDatas> lists = new ArrayList<>();
                for (ReconmmendSongDatas.ContentEntity entity : datas) {
                    MusicListDatas musicList = new MusicListDatas();
                    musicList.setName(entity.getTitle());
                    musicList.setSinger(entity.getAuthor());
                    musicList.setSongId(entity.getSong_id());
//                    musicList.setSingerImage(entity.get);
                    musicList.setFrom(context.getString(R.string.fromnet));
                    lists.add(musicList);
                }
                MainActivity.play(lists, position);
            }
        });
        holder.songDow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog myDialog = new AlertDialog.Builder(context).create();
                myDialog.show();
                Window window = myDialog.getWindow();
                window.setContentView(R.layout.my_dialog);

                Button love = (Button) window.findViewById(R.id.my_dialog_love);
                // 收藏的监听
                love.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
                // 分享的监听
                Button share = (Button) window.findViewById(R.id.my_dialog_share);
                share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

                download = (Button) window.findViewById(R.id.my_dialog_download);
                download.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        String id = songDats.getSong_id();
                        songsName = songDats.getTitle();
                        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid="+
                                                id +"&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                                "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";

                        JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                String str = response.toString();
                                SongInfors infors = JSON.parseObject(str, SongInfors.class);
                                String strUrl = infors.getSongurl().getUrl().get(0).getShow_link();
                                Log.i("downlaod",strUrl + "");
//                                if (strUrl != null) {
//                                    Intent intent = new Intent(context,DownloadActivity.class);
//                                    intent.putExtra("strUrl", strUrl);
//                                    context.startActivity(intent);
//
//                                }
                                if (!URLUtil.isNetworkUrl(strUrl)) {
                                    Toast.makeText(context, "错误的URL", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                               /* 文件会下载至local端 */
                                Toast.makeText(context, "下载中,请稍后...", Toast.LENGTH_SHORT).show();
                                download.setEnabled(false);
                                 /* 取得欲安装程序之文件名称 */
                                fileEx = strUrl.substring(strUrl.lastIndexOf(".") + 1,
                                        strUrl.length());
                                fileNa = strUrl.substring(strUrl.lastIndexOf("/") + 1,
                                        strUrl.lastIndexOf("."));
                                Log.i(TAG, "fileNa:" + fileNa);
                                getFile(strUrl);
                                initNotification();
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });
                        volleySingleton.addQueue(jr,"PlayerService");
                    }

                });

                Button cancel = (Button) window.findViewById(R.id.my_dialog_cancel);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                });
                window.setLayout(700, 500);

            }
        });
        return convertView;
    }



    public class ViewHolder
    {
        private TextView songsNames,authersName;
        private ImageView songDow;
        private LinearLayout itemSongListView;
    }


    private void initNotification() {
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotification = new Notification();
        mNotification.icon = R.mipmap.d_icon;// 设置通知消息的图标
        mNotification.tickerText = "正在下载。。。";// 设置通知消息的标题
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        mRemoteViews = new RemoteViews(context.getPackageName(),
                R.layout.down_notification);

//        PendingIntent pi = PendingIntent.getActivity(context, 0, Intent.getIntent(), 0);
//        mNotification.contentIntent = pi;
    }

    /* 处理下载URL文件自定义函数 */
    private void getFile(final String strPath) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    getSourceData(strPath);
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        }).start();
    }

    private FileUtils mFileUtils;

    /* 取得远程文件 */
    private void getSourceData(String strPath) throws Exception {

        mFileUtils = new FileUtils();
        mFileUtils.setDownloadCallBack(mDownloadCallBack);
        File myTempFile = mFileUtils.getData(strPath, "TestDownload", fileNa
                + "." + fileEx);

        /* 打开文件进行安装 */
        openFile(myTempFile);

    }
    /* 在手机上打开文件的method */
    private void openFile(File f) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        /* 调用getMIMEType()来取得MimeType */
        String type = getMIMEType(f);
        /* 设置intent的file与MimeType */
        intent.setDataAndType(Uri.fromFile(f), type);
        context.startActivity(intent);
        clearNotification();
    }

    /* 判断文件MimeType的method */
    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();

        /* 依扩展名的类型决定MimeType */
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else {
            type = "*/*";
        }

        return type;
    }

    private Handler mHandler = new Handler();
    private Runnable mProgressTask = new Runnable() {

        @Override
        public void run() {
            long readed = mFileUtils.getReaded();
            long all = mFileUtils.getAllSize();
            StringBuffer sb = new StringBuffer("下载中...");
            sb.append(readed);
            sb.append("kb");
            sb.append("/");
            sb.append(all);
            sb.append("kb");


            if (readed < all) {
                mRemoteViews.setTextViewText(R.id.app_name,songsName);
                mRemoteViews.setTextViewText(R.id.progressTv, sb.toString());
                int size = (int) (readed * 100 / all);
                mRemoteViews.setProgressBar(R.id.progressBar, 100, size, false);
                mNotification.contentView = mRemoteViews;
                mNotificationManager.notify(mNotificationID, mNotification);
                mHandler.postDelayed(mProgressTask, 500);
            } else {
                mRemoteViews.setTextViewText(R.id.app_name,songsName);
                mRemoteViews.setTextViewText(R.id.progressTv, "下载完成");
                mRemoteViews.setProgressBar(R.id.progressBar, 100, 100, false);
                mNotification.contentView = mRemoteViews;
                mNotificationManager.notify(mNotificationID, mNotification);
                Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
                clearNotification();
                download.setEnabled(true);


            }
        }
    };

    private FileUtils.DownloadCallBack mDownloadCallBack = new FileUtils.DownloadCallBack() {

        @Override
        public void onStart() {
            mHandler.postDelayed(mProgressTask, 500);

        }

        @Override
        public void onCompleted() {


        }
    };

    //删除通知
    private void clearNotification(){
        // 启动后删除之前我们定义的通知
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(1);

    }
}
